'''
https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/
'''


class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        times = [0] * 256
        l = r = 0
        distance = 0
        n = len(s)
        ans = 0
        while r < n:
            while r < n and distance == 0:
                times[ord(s[r])] += 1
                if times[ord(s[r])] > 1:
                    distance += 1
                r += 1
            ans = max(ans, r - l - 1) if distance else max(ans, r - l)
            while l <= r and distance:
                times[ord(s[l])] -= 1
                if times[ord(s[l])] == 1:
                    distance -= 1
                l += 1
        return ans

    def lengthOfLongestSubstring2(self, s: str) -> int:
        last = [-1] * 256
        ans = 0
        l, r, n = 0, 0, len(s)
        while r < n:
            l = max(l, last[ord(s[r])] + 1)     # 更新左边界，到一个正确的位置
            ans = max(ans, r - l + 1)
            last[ord(s[r])] = r
            r += 1
        return ans

s = 'pwwkew'
print(Solution().lengthOfLongestSubstring2(s))
print(Solution().lengthOfLongestSubstring(s))